package com.icesoft.framework.core.log;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class LogHandleServer implements ApplicationRunner {

	@Autowired(required = false)
	List<ILogMessageListener> listeners;
	Thread thread;

	@Override
	public void run(ApplicationArguments args) throws Exception {
		thread = new Thread(() -> {
			if (listeners == null) {
				log.info("no ILogMessageListener bean");
				return;
			}
			LogFilter.USED = true;
			while (!Thread.currentThread().isInterrupted()) {
				try {
					LogMessage logMsg = LoggerQueue.getInstance().poll();
					if (logMsg != null) {
						for (ILogMessageListener iLogMessageListener : listeners) {
							try {
								iLogMessageListener.handle(logMsg);
							} catch (Exception e) {
								log.error("处理日志异常", e);
							}

						}
					}
				} catch (Exception e) {
					log.info("LogHandleServer InterruptedException");
					break;
				}
			}
			LogFilter.USED = false;
			log.info("控制台日志打印线程退出...");
		});
		thread.setName("LogHandleServer");
		thread.start();
	}

}
